﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices;
using System.Windows.Threading;
using ALiteTeam.PackageTracer.Core;
using System.IO.IsolatedStorage;
using System.Windows.Media.Imaging;
using GalaSoft.MvvmLight.Messaging;
using ALiteTeam.PackageTracer.ViewModel;

namespace ALiteTeam.PackageTracer.View.Pages
{
    public partial class Scaner : PhoneApplicationPage
    {
        private BarCodeIdentifier _Identifier;
        private PhotoCamera _Camera;

        private DispatcherTimer _Timer;

        public Scaner()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (_Camera == null)
            {
                progressBar.IsIndeterminate = true;
                _Camera = new PhotoCamera();
                _Timer = new DispatcherTimer();
                _Timer.Interval = TimeSpan.FromMilliseconds(300);

                _Camera.Initialized += new EventHandler<CameraOperationCompletedEventArgs>(camera_Initialized);


                _Timer.Tick += new EventHandler(_Timer_Tick);

                this.viewfinderBrush.SetSource(_Camera);
            }

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            _Camera.Dispose();
            _Camera = null;

            base.OnNavigatedFrom(e);
        }

        void _Timer_Tick(object sender, EventArgs e)
        {
            var result = _Identifier.Identify(_Camera);
            if (string.IsNullOrEmpty(result) == false)
            {
                _Timer.Stop();

                Settings.AppContext.CurrentDeliveryOrder.OrderNo = result;

                Messenger.Default.Send<Guid>(Settings.AppContext.CurrentDeliveryOrder.DeliveryID, InputOrderViewModel.INITIALIZE);
                NavigationService.GoBack();
            }
        }

        private void camera_Initialized(object sender, CameraOperationCompletedEventArgs e)
        {
            if (e.Succeeded)
            {
                _Camera.FlashMode = FlashMode.Off;
                _Identifier = new BarCodeIdentifier();

                this.Dispatcher.BeginInvoke(delegate()
                {
                    progressBar.IsIndeterminate = false;
                    lblTips.Text = "请将条码尽量放到屏幕中心，触屏对焦";

                    this.videoRectangle.Width = this.ActualWidth;
                    this.videoRectangle.Height = this.ActualHeight;

                    this.internalRectangle.Width = this.LayoutRoot.ActualWidth - 50;
                    this.internalRectangle.Height = this.LayoutRoot.ActualHeight - 500;

                    this.internalRectangle.Visibility = System.Windows.Visibility.Visible;
                    this.lineRed.Visibility = System.Windows.Visibility.Visible;

                    this.previewTransform.Rotation = _Camera.Orientation;
                });
            }
        }

        private void LayoutRoot_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            if (_Camera.IsFocusAtPointSupported == true)
            {
                Point point = e.GetPosition(this.videoRectangle);

                // Determine the focus point.
                double focusXPercentage = point.X / videoRectangle.Width;
                double focusYPercentage = point.Y / videoRectangle.Height;

                _Camera.FocusAtPoint(focusXPercentage, focusYPercentage);
            }
            else
            {
                _Camera.Focus();
            }

            if (this._Timer.IsEnabled == false)
            {
                this._Timer.Start();
            }
        }
    }
}